package org.example.exception;


import org.example.common.ErrorResponse;
import org.springframework.boot.context.properties.bind.BindException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.EOFException;

import static org.example.common.R.ok;
import static org.example.common.ResponseEnum.SUCCESS;

/**
 * @version 1.0
 * @description TODO
 * @date 2024/10/14 23:27
 */

@ControllerAdvice
class GlobalExceptionController {
    @ExceptionHandler(MyException.class)
    @ResponseBody
    public ResponseEntity<ErrorResponse> handleMyException(MyException e) {
        ErrorResponse errorResponse = new ErrorResponse(e.getCode(), e.getMessage());
        return new ResponseEntity<>(errorResponse,HttpStatus.NOT_IMPLEMENTED);
    }



    @ExceptionHandler(value = RuntimeException.class)
    @ResponseBody
    public ResponseEntity<ErrorResponse> baseExceptionHandler(Exception e) {
        ErrorResponse errorResponse = new ErrorResponse("500", e.getMessage());

        return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @ExceptionHandler(BindException.class)
    @ResponseBody
    public ResponseEntity<ErrorResponse> handleBadRequestException(BindException ex) {
        ErrorResponse error = new ErrorResponse("501", ex.getMessage());
        return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST);
    }

    @ExceptionHandler(NullPointerException.class)
    @ResponseBody
    public ResponseEntity<ErrorResponse> handleBadRequestException(NullPointerException ex) {
        ErrorResponse error = new ErrorResponse("503", ex.getMessage());
        return new ResponseEntity<>(error, HttpStatus.FORBIDDEN);
    }


    // 2. 使用@ExceptionHandler定义异常处理方法
        // 处理自定义异常
        @ExceptionHandler(EOFException.class)
        @ResponseBody
        public ResponseEntity<ErrorResponse> handleCustomNotFoundException(EOFException ex) {
            ErrorResponse error = new ErrorResponse("NotFound", ex.getMessage());
            return new ResponseEntity<>(error, HttpStatus.NO_CONTENT);
        }

        // 处理所有400类异常


        // 处理所有500类异常
        @ExceptionHandler(Exception.class)
        @ResponseBody
        public ResponseEntity<ErrorResponse> handleException(Exception ex) {
            ErrorResponse error = new ErrorResponse("ServerError", "Internal Server Error");
            return new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }




